<template>
  <div class="dashboard-container" v-loading="loading">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-content">
            <div class="card-title">今日订单</div>
            <div class="card-value">{{ todayOrders }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-content">
            <div class="card-title">今日销售额</div>
            <div class="card-value">¥{{ formatNumber(todaySales) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-content">
            <div class="card-title">商品总数</div>
            <div class="card-value">{{ totalProducts }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-content">
            <div class="card-title">用户总数</div>
            <div class="card-value">{{ totalUsers }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售趋势图 -->
    <el-row class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>销售趋势图</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="salesChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近订单列表 -->
    <el-row>
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近订单列表</span>
            </div>
          </template>
          <el-table :data="latestOrders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="180"/>
            <el-table-column prop="amount" label="金额" width="150">
              <template #default="scope">
                ¥{{ formatNumber(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="时间" width="180"/>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  getDashboardOverview,
  getSalesStats,
  getLatestOrders
} from '@/api/dashboard'
import { formatNumber, getOrderStatusType, getOrderStatusText } from '@/utils/format'
import { showError } from '@/utils/message'

// 注册必须的组件
use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

// 响应式数据
const loading = ref(false)
const todayOrders = ref(0)
const todaySales = ref(0)
const totalProducts = ref(0)
const totalUsers = ref(0)
const latestOrders = ref([])

// 销售趋势图表配置
const salesChartOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    name: '销售额',
    axisLabel: {
      formatter: '¥{value}'
    }
  },
  series: [
    {
      name: '销售额',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
})

// 自动刷新定时器
let refreshTimer = null
const REFRESH_INTERVAL = 5 * 60 * 1000 // 5分钟刷新一次

// 获取概览数据
const fetchOverview = async () => {
  try {
    const { data } = await getDashboardOverview()
    todayOrders.value = data.todayOrders
    todaySales.value = data.todaySales
    totalProducts.value = data.totalProducts
    totalUsers.value = data.totalUsers
  } catch (error) {
    showError('获取概览数据失败')
    console.error('获取概览数据失败:', error)
  }
}

// 获取销售统计数据
const fetchSalesStats = async () => {
  try {
    const { data } = await getSalesStats()
    salesChartOption.value.xAxis.data = data.dates
    salesChartOption.value.series[0].data = data.sales
  } catch (error) {
    showError('获取销售统计数据失败')
    console.error('获取销售统计数据失败:', error)
  }
}

// 获取最新订单数据
const fetchLatestOrders = async () => {
  try {
    const { data } = await getLatestOrders({ limit: 10 })
    latestOrders.value = data
  } catch (error) {
    showError('获取最新订单数据失败')
    console.error('获取最新订单数据失败:', error)
  }
}

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchOverview(),
      fetchSalesStats(),
      fetchLatestOrders()
    ])
  } catch (error) {
    showError('初始化数据失败')
    console.error('初始化数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  initData()
}

// 启动自动刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(refreshData, REFRESH_INTERVAL)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

onMounted(() => {
  initData()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-content {
  text-align: center;
  padding: 20px;
}

.card-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin: 20px 0;
}

.chart-container {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}
</style> 